package servlet;

import dao.UserDao;
import dao.impl.UserDaoImpl;
import domain.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;

/**
 * LoginServlet实现类
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public LoginServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 获取前端页面传过来的值
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 执行查询数据库逻辑
        UserDaoImpl userDao = new UserDaoImpl();
        User user = userDao.login(username, password);

        // 如果根据用户名和密码能查得到值
        if (user != null) {
            session.setAttribute("user", user);        //登录成功
            request.getRequestDispatcher("/login_success.jsp").forward(request, response);
        } else {    // 用户名或者密码错误执行以下代码
            request.setAttribute("message", userDao.Back());
            request.getRequestDispatcher("/defeat.jsp").forward(request, response);
        }
    }

}